<script>
import emoji from "@/assets/emoji";
import {findByUserName, findUnreadNums, selectOnlineInquiryPatientList} from "@/api/chatRecord";
import {download} from "@/api/file";

let client;
export default {
  name: "OnlineInquiry",
  data() {
    return {
      user: {},
      headers: {},
      fileUploadUrl: this.baseUrl + "/file/upload",
      emojis: [],
      messages: [],
      onlineInquiryPatientList: [],
      sender: '',
      receiver: '',
      receiverAvatar: '',
      unread: {}
    }
  },
  mounted() {
    this.emojis = emoji.split(',');
    this.user = JSON.parse(localStorage.getItem('user') || "{}");
    this.headers = {token: this.user ? this.user.token : null};
    this.sender = this.user.role + '_' + this.user.userName;
    client = new WebSocket(process.env.NODE_ENV==='development'?`ws://localhost:8089/imServer`:`ws://47.116.78.187:8088/imServer`);
    client.onopen = () => {
      console.log('websocket open');
    };
    client.onclose = () => {
      console.log('websocket close');
    };
    client.onmessage = (msg) => {
      if (msg.data) {
        let json = JSON.parse(msg.data);
        if (json.content && (json.sender === this.sender && json.receiver === this.receiver) || json.receiver === this.sender && json.sender === this.receiver) {
          this.messages.push(json);
          this.scrollToBottom();
        }
        if (this.receiver === json.sender) {
          this.setUnreadNums();
        } else {
          this.loadUnreadNums();
        }
      }
    };
    this.load();
    selectOnlineInquiryPatientList(this.sender).then(res => {
      this.onlineInquiryPatientList = res.data;
      console.log(this.onlineInquiryPatientList)
    })
  },
  beforeDestroy() {
    if (client) {
      client.close();
    }
  },
  methods: {
    load() {
      let params = {
        sender: this.sender,
        receiver: this.receiver
      }
      findByUserName(params).then(res => {
        if (res.code === 200) {
          this.messages = res.data;
          this.scrollToBottom();
        } else {
          this.$message({
            message: res.msg,
            type: 'error',
            center: true
          })
        }
        this.loadUnreadNums();
      })
    },
    setUnreadNums() {
      let params = {
        sender: this.sender,
        receiver: this.receiver
      }
      findByUserName(params).then(res => {
        if (res.code === 200) {
          this.loadUnreadNums();
        } else {
          this.$message({
            message: res.msg,
            type: 'error',
            center: true
          })
        }
      })
    },
    loadUnreadNums() {
      findUnreadNums(this.sender).then(res => {
        if (res.code === 200) {
          this.unread = res.data;
        } else {
          this.$message({
            message: res.msg,
            type: 'error',
            center: true
          })
        }
      })
    },
    send() {
      if (!this.receiver) {
        this.$message({
          message: '请选择一位医生进行咨询',
          type: 'error',
          center: true
        })
        return;
      }
      if (client) {
        let message = this.getMessage("text");
        client.send(JSON.stringify(message));
      }
      document.getElementById('im-content').innerHTML = '';

    },
    selectReceiver(item) {
      console.log(item);
      this.receiver = item.role + '_' + item.userName;
      this.receiverAvatar = item.avatar;
      this.load();
    },
    getMessage(type) {
      let inputBox = document.getElementById('im-content');
      const content = inputBox.innerHTML;
      if (!content && type === 'text') {
        this.$message({
          message: '请输入咨询内容',
          type: 'error',
          center: true
        })
        return;
      }
      return {
        sender: this.sender,
        senderAvatar: this.user.avatar,
        receiver: this.receiver,
        receiverAvatar: this.receiverAvatar,
        content: content,
        type: type
      }
    },
    download(url) {
      download(url).then(res => {
        console.log(res)
        const blob = new Blob([res.data], {type: "application/octet-stream;charset=utf-8"})
        const downloadElement = document.createElement("a");
        const href = window.URL.createObjectURL(blob);
        downloadElement.href = href;
        downloadElement.download = decodeURI(
            res.headers["content-disposition"].split("filename=")[1]);
        document.body.appendChild(downloadElement);
        downloadElement.click();
        document.body.removeChild(downloadElement);
        window.URL.revokeObjectURL(href);
      })
    },
    handleFile(res) {
      if (client) {
        let message = this.getMessage('img');
        message.content = res.data;
        let extName = res.data.substring(res.data.lastIndexOf('.') + 1);
        if (['png', 'jpg', 'jpeg', 'gif', 'bmp', 'tiff', 'svg', 'webp'].includes(extName)) {
          message.type = 'img';
        } else {
          message.type = 'file';
        }
        client.send(JSON.stringify(message));
      }
    },
    clickEmoji(emoji) {
      document.getElementById('im-content').innerHTML += emoji
    },
    scrollToBottom() {
      this.$nextTick(() => {
        let imMessageBox = document.getElementsByClassName('im-message-box')[0];
        imMessageBox.scrollTop = imMessageBox.scrollHeight;
        console.log("触发滚动")
      })
    }
  }
}
</script>

<template>
  <div>
    <div class="main-body-content">
      <div style="display: flex;align-items: flex-start">
        <div class="list-box"
             style="width: 200px; border: 1px solid #ddd; border-radius: 5px; height: calc(50vh + 125px)">
            <div style="padding: 10px; border-bottom: 1px solid #ddd; color: #000; background-color: #eee">
              患者
            </div>
            <div class="patient-list-box" >
              <div class="patient-list-item" v-for="patient in onlineInquiryPatientList" @click="selectReceiver(patient.user)">
                <img :src="patient.user.avatar" style="width: 30px;height:30px;border-radius: 50%"/>
                <span style="flex:1;margin-left: 10px"
                      :style="{color:patient.user.role+'_'+patient.user.userName===receiver?'#3a8ee6':''}">{{ patient.user.userName }}</span>
                <div class="patient-list-item-badge" v-if="unread?.[patient.user.role+'_'+patient.user.userName]">{{unread?.[patient.user.role+'_'+patient.user.userName]}}</div>
              </div>
            </div>
        </div>
      <div style="width: 50%;border: 1px solid #ddd; border-radius: 5px; background-color: #f1f1f1; margin: 0 10px;" v-if="receiver!=''">
        <div style="padding: 20px 0; text-align: center; border-bottom: 1px solid #ddd; color: #000; background-color: #eee; height: 60px">
          {{receiver?.substring(receiver.lastIndexOf('_')+1)}}
        </div>
        <div class="im-message-box">
        <div v-for="item in messages" :key="item.id">
         <div style="display: flex; flex-direction: row-reverse; align-items: flex-start" v-if="item.sender===sender">
         <img :src="item.senderAvatar" style="width: 40px;height: 40px;border-radius: 50%;margin-left:10px "/>
           <div class="im-message im-message-right" v-html="item.content"
                v-if="item.type === 'text'"></div>
           <div class="im-message" style="padding: 0" v-if="item.type === 'img'">
             <!-- 注意  el-image 的load函数必须加上，否则无法触发滚动条到最底端 -->
             <el-image style="width: 100px" :src="item.content" alt=""
                       :preview-src-list=[item.content] @load="scrollToBottom"></el-image>
           </div>
           <div class="im-message im-message-download" v-if="item.type === 'file'"
                @click="download(item.content)">
             <div><i class="el-icon-folder-opened"></i>
               <span>{{ item.content.substring(item.content.lastIndexOf('/') + 1) }}</span>
             </div>
           </div>
         </div>
          <div style="display: flex; align-items: flex-start" v-else>
        <img :src="item.senderAvatar" style="width:40px;height:40px;border-radius: 50%;margin-right: 10px"/>
            <div style="width: 100%">
              <div style="color: #888; font-size: 12px; width: 50%">
              {{item.sender?.substring(item.sender.lastIndexOf('_')+1)}}
              </div>
              <div class="im-message im-message-left" v-html="item.content"
                   v-if="item.type === 'text'"></div>
              <div class="im-message" style="padding: 0" v-if="item.type === 'img'">
                <!-- 注意  el-image 的load函数必须加上，否则无法触发滚动条到最底端 -->
                <el-image style="width: 100px" :src="item.content" alt=""
                          :preview-src-list=[item.content] @load="scrollToBottom"></el-image>
              </div>
              <div class="im-message im-message-download" v-if="item.type === 'file'"
                   @click="download(item.content)">
                <div><i class="el-icon-folder-opened"></i>
                  <span>{{ item.content.substring(item.content.lastIndexOf('/') + 1) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        </div>
        <div style="padding: 10px 5px; border-top: 1px solid #ddd; display: flex; align-items: center; width: 100%;">
          <el-popover placement="top" width="300" trigger="click">
            <div class="emoji-box">
                <span v-for="(item, index) in emojis" :key="index"
                      style="margin-right: 5px; font-size: 20px; cursor: pointer" v-html="item"
                      @click="clickEmoji(item)">
                </span>
            </div>
            <i slot="reference" class="el-icon-biaoqing" style="font-size: 22px; color: #666;"></i>
          </el-popover>
          <div style="margin-left: 5px">
            <el-upload :action="fileUploadUrl" :headers="headers"  :show-file-list="false" :on-success="handleFile">
              <i class="el-icon-folder-opened" style="font-size: 20px; color: #666;"></i>
            </el-upload>
          </div>
          <div id="im-content"  class="im-content" contenteditable
               style="flex: 1; background-color: #fff; margin: 0 5px; padding: 10px; border: 1px solid #ddd; border-radius: 2px; outline: none; font-size: 14px;overflow-y: scroll;height: 82px"></div>
          <el-button type="primary" @click="send" style="border: none">发送</el-button>
        </div>
      </div>
        <div class="im-message-empty"style="width: 50%;border: 1px solid #ddd; border-radius: 5px; background-color: #fff;; margin: 0 10px;height:66vh;" v-else>
          <el-empty :image-size="200" description="请选择患者进行回复"></el-empty>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.list-box{
  background-color: #FFFFFF;
}
.im-message-box{
  height:45vh;
  padding: 10px;
  overflow-y: auto;
  overflow-x: hidden;
  background-color: #FFFFFF;
}

.im-message {
  font-size: 14px;
  padding: 10px;
  margin: 5px 0;
  border-radius: 5px;
  color: #000;
  max-width: 50%;
  word-break: break-all;
  word-wrap: break-word;
  line-height: 20px;
  width: fit-content;
}
.emoji-box {
  height: 200px;
  overflow-y: scroll;
  line-height: 30px;
}
.im-message-left {
  background-color: #DBEDFF;
}

.im-message-right {
  background-color: #26d470;
}

.im-message-download {
  background-color: #239fff;
  max-width: 80%;
  cursor: pointer;
}
.patient-list-box {
  overflow-y: auto;
  background-color: #FFFFFF;
}

.patient-list-box::-webkit-scrollbar,.emoji-box::-webkit-scrollbar,.im-message-box::-webkit-scrollbar{
  width: 4px;
}

.im-content::-webkit-scrollbar{
  width: 1px;
}

 .patient-list-box::-webkit-scrollbar-thumb,.emoji-box::-webkit-scrollbar-thumb,.im-message-box::-webkit-scrollbar-thumb,.im-content::-webkit-scrollbar-thumb{
  border-radius: 10px;
  background: rgba(0, 0, 0, 0.1);
}

 .patient-list-box::-webkit-scrollbar-track ,.emoji-box::-webkit-scrollbar-track,.im-message-box::-webkit-scrollbar-track,.im-content::-webkit-scrollbar-track{
  border-radius: 0;
  background: rgba(0, 0, 0, 0.1);
}

.patient-list-item {
  display: flex;
  padding: 10px;
  align-items: center;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  font-size: 14px;
}

.patient-list-item-badge {
  padding: 2px 6px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: white;
  background-color: red;
}

.patient-list-item:nth-last-child(1) {
  border: none;
}
</style>